/**
 * Unicorn Admin Template
 * Diablo9983 -> diablo9983@gmail.com
**/
$(document).ready(function(){

    var code ; //在全局 定义验证码
    function createCode()
    {
        code = "";
        var codeLength = 4;//验证码的长度
        var checkCode = document.getElementById("verifyid1");
        var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');//所有候选组成验证码的字符，当然也可以用中文的

        for(var i=0;i<codeLength;i++)
        {
            var charIndex = Math.floor(Math.random()*36);
            code +=selectChar[charIndex];
        }
        if(checkCode)
        {
            checkCode.className="span1 code";
            checkCode.innerHTML = code;
        }
    }

    createCode();

    $("#verifyc").click(function(){createCode();});

    $("#loginform").validate({
        onsubmit:true,// 是否在提交是验证
        rules:{
            uname:{
                required:true
            },
            passwd:{
                required:true,
                maxlength:32,
                minlength:3
            }
        },
        errorClass: "help-inline",
        errorElement: "row",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.row').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.row').removeClass('error');
            $(element).parents('.row').addClass('success');
        },

        submitHandler: function(form) {  //通过之后回调
            var ccode=document.getElementById("verifyid1").innerHTML.toLowerCase();
            if(ccode.toLowerCase() !== document.getElementById("verifyid").value.toLowerCase())
            {
                $("#loginstatus").show();
                $("#loginstatus").html("登录失败：验证码输入错误");
                createCode();
                return false;
            }

            var param = $("#loginform").serialize();
            $.ajax({
                url : "login.html",
                type : "post",
                dataType : "json",
                data: param,
                success : function(result) {
                    if(result.success==true)
                    {
                        location = result.url;
                    }
                    else
                    {
                        $("#loginstatus").show();
                        $("#loginstatus").html(result.info);
                        createCode();
                    }
                }
            });
        },
        invalidHandler: function(form, validator) {  //不通过回调
            return false;
        }
    });
});